<template>
	<view class="pages">
	</view>
</template>
<script>
	export default {
		data() {
			return {}
		},
		computed: {},
		onReady() {},
		onShow() {},
		onLoad() {
			
			// #ifdef H5
			this.authjssdkH5()
			// #endif
		},
		methods: {
			authjssdkH5() {
				console.log('auth-jssdk onload');
				if (this.$jssdk.isWechat()) {
					let local = window.location.href; // 获取页面url
					let level_uri = '/h5'
					let level = this.$wanlshop.config('level')
					if (level == 2) {
						level_uri = '/worker'
					} else if (level == 1) {
						if (this.$api.config.baseUrl == 'https://test.aibbyp.com/api') {
							// 重定向到 test 环境
							level_uri = '/devh5'
						} else if (this.$api.config.baseUrl == 'https://h5.aibbyp.com/api') {
							// 重定向到 生产环境
							level_uri = '/h5'
						}
					}
					// level_uri = '/localhost' //本地测试
					local = 'https://mp.aibbyp.com' + level_uri + window.location.pathname + window.location.search
					let code = this.getUrlCode().code; // 截取code
					// 获取之前的code
					let oldCode = uni.getStorageSync('wanlshop:code');
					// 如果没有code，就去请求获取code
					if (code == null || code === '' || code == undefined || code == oldCode) {
						let uri = encodeURIComponent(local);
						uni.setStorageSync('wanlshop:code', 0); // 设置旧的code为0，避免死循环
						let href =
							`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.$wanlshop.config('appid')}&redirect_uri=${uri}&response_type=code&scope=snsapi_base#wechat_redirect`

						window.location.href = href
					} else {
						let pageroute = this.getUrlCode().state; // 截取state
						uni.setStorageSync('wanlshop:code', code); // 保存最新code
						this.$api.post({
							url: '/wanlshop/user/third',
							loadingTip: '微信登录中...',
							data: {
								platform: 'h5_weixin',
								code: code,
								// client_id: uni.getStorageSync("wanlshop:chat_client_id") ? uni.getStorageSync("wanlshop:chat_client_id") : null
							},
							success: res => {
								console.log('网页登录', res);
								uni.setStorageSync("wanlshop:user", res.userinfo);
								this.$store.dispatch('user/login', res);
								this.$store.dispatch('cart/login');
								uni.reLaunch({
									url: '/pages/tabbarcompotant/index/landlord'
								});
							}
						});
					}
				} else {}
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				// this.winUrl = url;
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;
			},
		}
	}
</script>

<style scoped></style>